<template>
  <div>
    <el-dialog v-model="dialogVisible" title="公众号模板消息群发" width="30%">
      <el-form ref="mpFormRef" :model="mpForm" label-width="100px" :rules="rules">
        <el-form-item label="目标对象："> 已选择 {{ mpForm.num }} 人 </el-form-item>
        <el-form-item label="任务名称：" prop="taskName">
          <el-input
            v-model="mpForm.taskName"
            placeholder="请输入任务名称"
            :style="{ width: '50%' }"
          />
        </el-form-item>
        <el-form-item label="模板类型：" prop="templateType">
          <el-select
            v-model="mpForm.templateType"
            placeholder="请选择模板类型"
            :style="{ width: '50%' }"
          >
            <el-option
              v-for="item in templateTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板选择：" v-if="mpForm.templateType" prop="templateCode">
          <el-select v-model="mpForm.priTmplId" placeholder="请选择模板" :style="{ width: '50%' }">
            <el-option
              v-for="item in templateSelectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="模板内容：" v-if="mpForm.priTmplId">
          <div class="content">{{ templateContent }}</div>
        </el-form-item>
        <el-form-item v-if="mpForm.slotList && mpForm.slotList.length > 0" label="变量配置：">
          <view style="display: flex; flex-direction: column; row-gap: 0.5rem">
            <el-row v-for="item in mpForm.slotList" :key="item">
              <el-col :span="9">
                <el-input :value="item" disabled />
              </el-col>
              <el-col :span="14" :offset="1">
                <el-input v-model="mpForm.slots[item]" />
              </el-col>
            </el-row>
          </view>
        </el-form-item>
        <el-form-item>
          <el-button @click="mpBroadcastPreview">预览</el-button>
          <el-button type="primary" @click="mpBroadcastSend" :loading="btnLoading"
            >立即创建</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 短信预览 -->
    <el-dialog v-model="mpPreview" title="模板推送预览" width="20%">
      <view class="sms-preview">
        <view class="sms-preview__tips">仅预览第一条模板内容：</view>
        <view class="sms-preview__content">{{ templateContent }}</view>
        <view class="sms-preview__count"
          >模板字数：<text class="sms-preview__count__unit">{{ templateContent.length }}</text
          >字</view
        >
        <view class="sms-preview__count"
          >预计扣除模板条数：<text class="sms-preview__count__unit">1条</text></view
        >
        <el-button class="sms-preview__close" type="primary" @click="mpPreview = false"
          >关闭</el-button
        >
      </view>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import * as smsApi from '@/mock/scrm/accountUser/index.ts'
import { ElMessage } from 'element-plus'
const dialogVisible = ref(false) // 弹窗控制
const btnLoading = ref(false)
const mpPreview = ref(false) // 预览
const mpFormRef = ref({})
const mpForm = reactive({
  type: '', // 类型 是否勾选了用户 val: check | uncheck
  taskName: '', // 任务名称
  slotList: [], // 变量插槽列表
  slots: {}, // 变量插槽json
  params: [], /// 外部传进来：用户openid列表 | 查询参数
  priTmplId: '', // 模板id
  num: 0,
  templateType: '' // 模板类型
})
const templateTypeOptions = ref([]) // 模板类型列表
const templateSelectOptions = ref([]) // 模板列表
const rules = reactive({
  taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  templateType: [{ required: true, message: '请选择模板类型', trigger: 'blur' }],
  priTmplId: [{ required: true, message: '请选择模板', trigger: 'blur' }]
})

const emits = defineEmits('sended')

/** 打开弹窗 */
const open = async (type: 'check' | 'uncheck', params: string[], num: number) => {
  resetmpForm() // 重置数据
  mpForm.num = num
  mpForm.params = params
  // 获取模板列表
  templateTypeOptions.value = await getMpTemplate()
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 模板类型发生变化时，渲染模板列表
watch(
  () => mpForm.templateType,
  (val) => {
    const result = templateTypeOptions.value.find((item) => item.value == val)
    result.list.forEach((item) => {
      item['label'] = item.title
      item['value'] = item.priTmplId
    })
    templateSelectOptions.value = result.list
    mpForm.priTmplId = ''
    mpForm.slotList = []
    mpForm.slots = {}
  }
)

// 获取模板列表
const getMpTemplate = async (arr: Array) => {
  let res = await smsApi.getMpTemplate()
  let result = res.data.map((item) => {
    item['label'] = item.name
    item['value'] = item.type
    return item
  })
  return result
}

// 获取模板内容
const templateContent = computed(() => {
  // 更新模板内容
  let content = ''
  // templateSelectOptions.value.forEach((item) => {
  //   if (item.value == mpForm.priTmplId) {
  //     content = item.content
  //   }
  // })
  // // 根据模板内容更新插槽
  // if (mpForm.slotList.length == 0) mpForm.slotList = getSmsTemplateSlots(content)
  // if (mpForm.slots && Object.keys(mpForm.slots).length > 0) content = bindTemplate(content)
  return content
})

// 获取模板插槽
const getSmsTemplateSlots = (template) => {
  const slots = []
  const slotPattern = /\{\{(.+?).DATA\}\}/g
  while (true) {
    const match = slotPattern.exec(template)
    if (!match) break
    const slot = match[1]
    slots.push(slot)
  }
  return slots
}

// 简单替换模板字符串
const bindTemplate = (value) => {
  console.log('111', value)

  let result = value
  const slotPattern = /\{\{(.+?).DATA\}\}/g
  while (true) {
    const match = slotPattern.exec(value)
    console.log(match)

    if (!match) break
    const slot = match[1]
    result = result.replace(`{{${slot}.DATA}}`, mpForm.slots[slot] || `{{${slot}.DATA}}`)
  }
  return result
}

// 预览
const mpBroadcastPreview = () => {
  if (templateContent.value == '') {
    ElMessage.error('请先选择模板')
    return
  }
  mpPreview.value = true
}

// 重置mpForm数据
const resetmpForm = () => {
  mpForm.taskName = ''
  mpForm.slotList = []
  mpForm.slots = {}
  mpForm.params = []
  mpForm.priTmplId = ''
  mpForm.num = 0
  mpForm.type = 'uncheck'
  mpForm.templateType = ''
}

// 模板发送
const mpBroadcastSend = async () => {
  if (!mpFormRef.value) return
  await mpFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (Object.keys(mpForm.slots).length != mpForm.slotList.length) {
        ElMessage.error('请完整填写模板变量！')
        return
      }
      let params = null
      btnLoading.value = true
      const template = templateSelectOptions.value.find(
        (item) => item.priTmplId == mpForm.priTmplId
      )
      if (mpForm.type == 'check') {
        // 请求参数
        params = {
          taskName: mpForm.taskName,
          touser: mpForm.params,
          templateId: mpForm.priTmplId,
          page: template!.url,
          contentJson: mpForm.slots,
          miniProgramAppid: template!.miniProgramAppid,
          miniProgramPagepath: template!.miniProgramPagepath
        }
      } else if (mpForm.type == 'uncheck') {
        // 请求参数
        params = {
          taskName: mpForm.taskName,
          queryParams: mpForm.params,
          templateId: mpForm.priTmplId,
          page: template!.url,
          contentJson: mpForm.slots,
          miniProgramAppid: template!.miniProgramAppid,
          miniProgramPagepath: template!.miniProgramPagepath
        }
      }
      // 发送模板消息
      if (mpForm.type == 'check') {
        await smsApi.sendTemplateFromUser(params)
      } else if (mpForm.type == 'uncheck') {
        await smsApi.sendTemplateFromQuery(params)
      }

      ElMessage.success('短信发送成功！')
      btnLoading.value = false
      dialogVisible.value = false
      emits('sended')
    } else {
      ElMessage.error('请完整填写信息！')
    }
  })
}
</script>

<style scoped lang="scss">
.content {
  white-space: pre-wrap;
  word-wrap: break-word;
}
.sms-preview {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  &__tips {
    margin-bottom: 0.5rem;
    color: #999;
  }

  &__content {
    width: 100%;
    padding: 0.5rem;
    margin-bottom: 1rem;
    border: 1px solid #ccc;
    border-radius: 0.25rem;
    font-size: 1rem;
    line-height: 1.5;
    box-sizing: border-box;
    white-space: pre-wrap;
    word-wrap: break-word;
  }

  &__count {
    align-self: flex-end;

    &__unit {
      color: #f56c6c;
    }
  }

  &__close {
    align-self: center;
    margin-top: 1rem;
  }
}
</style>
